//
//  SelectRegionViewController.m
//  YaDiuDiu
//
//  Created by 陈刚 on 2017/10/8.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "SelectRegionViewController.h"
#import "SelectRegionTableViewCell.h"

@interface SelectRegionViewController ()<UITableViewDataSource,UITableViewDelegate,BMKPoiSearchDelegate,CLLocationManagerDelegate,UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UITableView *regionTable;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;

@property (nonatomic, strong) BMKPoiSearch *searcher;

@property (strong,nonatomic) CLLocationManager *locationManager;

@property (nonatomic, strong) NSString *searchString;

@property (nonatomic, assign) CGFloat selfLongitude;

@property (nonatomic, assign) CGFloat selfLatitude;

@property (nonatomic, strong) NSMutableArray *addressArray;

@property (nonatomic, assign) int page;

@end

@implementation SelectRegionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
    
    self.searchString = @"小区";
    
    self.page = 1;
    
    [self startLocation];
    // Do any additional setup after loading the view from its nib.
}

-(void)startLocation{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager.delegate = self;
    
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    self.locationManager.distanceFilter = 100.0f;
    
    if ([[[UIDevice currentDevice]systemVersion]doubleValue] >8.0){
        
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    [self.locationManager startUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    self.selfLatitude = newLocation.coordinate.latitude;
    self.selfLongitude = newLocation.coordinate.longitude;
    [self loadData];
    [manager stopUpdatingLocation];
    
}

- (void)setupView{
    [self showNav:@"选择小区"];
    [self.regionTable registerNib:[UINib nibWithNibName:@"SelectRegionTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Cell"];
    self.regionTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadData];
    }];
    
    self.regionTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self loadData];
    }];
}

- (void)loadData{
    
    self.searcher = [[BMKPoiSearch alloc]init];
    [self.searcher setDelegate:self];
    
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    option.pageIndex = self.page;
    //当前索引页
    option.pageCapacity = 10;
    //分页量
    option.location = CLLocationCoordinate2DMake(self.selfLatitude, self.selfLongitude);
    option.keyword = self.searchString;
    option.radius = 3000;
    BOOL flag = [self.searcher poiSearchNearBy:option];
    if(flag) {
        NSLog(@"周边检索发送成功");
    } else {
        NSLog(@"周边检索发送失败");
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.addressArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)   indexPath{
    return 71;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    SelectRegionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SelectRegionTableViewCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BMKPoiInfo *item = [self.addressArray objectAtIndex:indexPath.row];
    [cell.nameLabel setText:item.name];
    [cell.addressLabel setText:item.address];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BMKPoiInfo *item = [self.addressArray objectAtIndex:indexPath.row];
    self.xiaoquSelect(item);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ======BMKPoiSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        NSArray *dataArray = poiResult.poiInfoList;
        if (self.page == 1) {
            self.addressArray = [poiResult.poiInfoList mutableCopy];
        }else{
            [self.addressArray addObjectsFromArray:dataArray];
        }
        [self.regionTable reloadData];
        [self.regionTable.mj_header endRefreshing];
        [self.regionTable.mj_footer endRefreshing];
        if (dataArray.count < 10) {
            [self.regionTable.mj_footer endRefreshingWithNoMoreData];
        }
        
    }
    
}

#pragma mark ========UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.searchString = self.searchBar.text;
    self.page = 1;
    [self loadData];
    [self.searchBar resignFirstResponder];
}

- (NSMutableArray *)addressArray{
    if (!_addressArray) {
        _addressArray = [[NSMutableArray alloc]init];
    }
    return _addressArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
